/**
 * LL长度指示类型
 * ASCII数字格式
 * 0-99
 */
package cc.rengu.igas.channel.cups.common.util;

import cc.rengu.igas.channel.cups.common.constant.CupsParamConstant;
import cc.rengu.jradp.exception.SystemException;
import cc.rengu.jradp.mods.trmsg.iso8583.FieldFactory;
import cc.rengu.jradp.mods.trmsg.iso8583.IsoTypeFactory;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @author lizhangtao
 * @date 2021/1/20
 */
@SuppressWarnings({"unused", "AlibabaClassNamingShouldBeCamel"})
public class DoubleLParseInfo extends IsoTypeFactory {
    private final static int LENGTH_LEN = 2;

    /**
     * ASCII格式，解析LL格式长度
     */
    @Override
    public FieldFactory decode(byte[] buf, int pos, Map<String, FieldFactory> fields, String index) {
        FieldFactory field = fields.get(index);
        if (pos < 0) {
            throw new SystemException("LL解析,位置非法pos=[" + pos + "]");
        } else if (pos + LENGTH_LEN > buf.length) {
            throw new SystemException("LL解析,位置非法pos=[" + pos + "+2] > message length[" + buf.length + "]");
        } else {
            for (int i = 0; i < LENGTH_LEN; i++) {
                //0-9
                if (buf[pos + i] < 48 || buf[pos + i] > 57) {
                    throw new SystemException("LL解析,字符格式非法," + buf[pos + i]);
                }
            }

            int length;
            length = ((buf[pos] - 48) * 10) + (buf[pos + 1] - 48);
            if (length > fields.get(index).getLength()) {
                throw new SystemException("LL解析,长度非法," + length);
            } else if (length < 0) {
                throw new SystemException("LL解析,长度非法," + length);
            }

            if (pos + LENGTH_LEN + length > buf.length) {
                throw new SystemException("LL解析,长度非法," + length);
            }
            field.setLenTypeLen(2);
            field.setLength(length);
            return field;
        }
    }

    /**
     * 默认不检查
     */
    @Override
    public boolean check(byte[] buf, int pos, Map<String, FieldFactory> fields, String index) {

        return true;
    }

    /**
     * LL长度指示类型设置长度值
     */
    @Override
    public FieldFactory encode(Map<String, FieldFactory> fields, String index) {
        FieldFactory field = fields.get(index);
        byte[] encodeByte;
        int lenTmp = field.getOrgValue().length - 1;
        try {
            encodeByte = String.format("%02d", lenTmp).getBytes(CupsParamConstant.GB18030);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new SystemException("不支持的编码格式" + CupsParamConstant.GB18030);
        }
        field.setOrgLenValue(encodeByte);
        field.setLenTypeLen(2);
        return field;
    }
}
